//
//  PassWordManageTool.m
//  JiaXiaoTong
//
//  Created by 沈增光 on 2017/11/1.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "PassWordManageTool.h"

#define  C1 520
#define  C2 1314
@implementation PassWordManageTool


//加密函数
+(NSString *)Encrypt:(NSString *)S withKey:(int)Key{
    
    
    Byte byteEncrypt[[S length]*2];
    
    
    for(int i=0; i<[S length]; i++) // 依次对字符串中各字符进行操作
    {
        
      
        unichar c=[S characterAtIndex:i]^(Key>>8);
        
           
        Byte b[2];
        b[0]=(Byte)((c&0xFF00)>>8);
        b[1]=(Byte)(c&0xFF);
        //[self IntToBytes:c with:b];
        byteEncrypt[i*2]=b[0];
        byteEncrypt[i*2+1]=b[1];
        //        NSLog(@"%d b[0]:%d  b[1]:%d",i,b[0],b[1]);
        
       
        Key = (Key>>8)*C1+C2;
        // 产生下一个密钥
    }
    
    
    
    NSData *plainData = [NSData dataWithBytes:byteEncrypt length:sizeof(byteEncrypt)/sizeof(char)];
    
    NSString *base64String = [plainData base64EncodedStringWithOptions:0];
    
    return base64String;
}


//解密函数
+(NSString *)Decrypt:(NSString *)S withKey:(int)Key{
    NSMutableString *Result=[[NSMutableString alloc]init];
    
    NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:S options:0];
    Byte *content=(Byte *)[decodedData bytes];
    
    int length= strlen(content)/2;
    
    for(int i=0; i<length; i++) // 依次对字符串中各字符进行操作
    {
        Byte b[2]={content[2*i],content[2*i+1]};
        unichar c= (unichar)(((b[0]& 0xff)<<8)| (b[1]&0xff));
        
        //         NSLog(@"jiemi c: %d",c);
        //         NSLog(@"%d b[0]: %d  b[1]:%d",i,content[2*i],content[2*i+1]);
        
        [Result appendString:[NSString stringWithFormat:@"%c", c^(Key>>8)]];
        
        Key = (Key>>8)*C1+C2;
    }
    return Result;
}
-(void)addtestcahnge {
    
    
    
}
@end
